package cn.reach.rpc.netty.client;

import cn.reach.rpc.AbstractInvokeRpcService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Netty RPC 客户端实现
 * 继承 AbstractInvokeRpcService 实现异步转同步功能
 */
public class NettyRpcClient extends AbstractInvokeRpcService<String, String> {
    private final String host;
    private final int port;
    private Channel channel;
    private final AtomicLong idGenerator = new AtomicLong(0);
    private final EventLoopGroup group = new NioEventLoopGroup();
    
    public NettyRpcClient(String host, int port) {
        this.host = host;
        this.port = port;
        init();
    }
    
    private void init() {
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new ClientHandler(NettyRpcClient.this));
                        }
                    });
            
            ChannelFuture future = bootstrap.connect(host, port).sync();
            channel = future.channel();
            System.out.println("Connected to server " + host + ":" + port);
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize client", e);
        }
    }
    
    @Override
    public long creatFutureId() {
        return idGenerator.incrementAndGet();
    }
    
    @Override
    public void sendRequest(long futureId, String param) {
        if (channel != null && channel.isActive()) {
            // 构建请求格式，例如：futureId|param
            String request = futureId + "|" + param;
            channel.writeAndFlush(request);
            System.out.println("Sent request: " + request);
        } else {
            throw new RuntimeException("Channel not active");
        }
    }
    
    public void close() {
        if (channel != null) {
            channel.close();
        }
        group.shutdownGracefully();
        System.out.println("Client closed");
    }
}